<script setup>
import * as APIShop from "@/api/store/store.js"
import { getLocalTime } from "@/utils/time.js"
import { ElMessage } from "element-plus"
import { onMounted, reactive, ref } from "vue"

//表格相关
const pn = ref(1)
const ps = ref(10)
const total = ref(0)
//存储店铺列表
const shopList = ref([])
//对话框可见性
const dialogFormVisible = ref(false)
//表单数据
let shopParams = reactive({
  id: null,
  name: null,
  address: null,
})

// 获取全部店长数据, 默认第一页
const pageFn = async (pager = 1) => {
  // 默认第一页，应对删空最后一页问题
  pn.value = pager
  const result = await APIShop.reqPageStore(
      pn.value,
      ps.value,
  )
  // 一些时间处理
  if (result.code === '0') {
    total.value = result.data.total
    shopList.value = []
    result.data.items.forEach(item => {
      shopList.value.push(item)
      shopList.value[shopList.value.length - 1].createTime = getLocalTime(item.createTime)
      shopList.value[shopList.value.length - 1].updateTime = getLocalTime(item.updateTime)
    })
  }
}

// 组件挂载，获取下拉框数据和表格数据
onMounted(() => {
  pageFn()
})

//添加分店按钮
const  addShop = () => {
  //显示对话框
  dialogFormVisible.value = true
  //清空表单数据
  Object.assign(shopParams,{
    id: null,
    name: null,
    address: null,
  })
  //清除表单验证提醒（目前还没做）
}

// 更新店长信息
const updateShop = (row) => {
  //显示对话框
  dialogFormVisible.value = true
  //收集已有信息
  // console.log(row)
  Object.assign(shopParams, row)
  //清除表单验证提醒（目前还没做）
}

//保存按钮的回调
const save = async () => {
  //表单验证（目前还没做）
  // 添加 | 更新信息
  if (shopParams.id) {
    //有id则为修改
    const result = await APIShop.reqUpdateStore({
      id: shopParams.id,
      name: shopParams.name,
      address: shopParams.address,
    })
    if (result.code === '0') {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      // window.location.reload();
      dialogFormVisible.value = false
      await pageFn()
    } else {
      //提示消息
      ElMessage({ type: 'error', message: shopParams.id ? '修改失败' : '添加失败' });
    }
  } else {
    //无id则为添加
    const result = await APIShop.reqSaveStore({
      name: shopParams.name,
      address: shopParams.address,
    })
    if (result.code === '0') {
      ElMessage({ type: 'success', message: "添加成功！"});
      dialogFormVisible.value = false
      await pageFn()
    } else {
      dialogFormVisible.value = false
      //提示消息
      ElMessage({ type: 'error', message: shopParams.id ? '修改失败' : '添加失败' });
    }
  }
  // 添加 | 更新成功
}

//取消按钮的回调
const cancel = () => {
  //关闭对话框
  dialogFormVisible.value = false
}

//删除店铺
const deleteShop = async (id) => {
  const result= await APIShop.reqDeleteStoreById(id)
  if (result.code === '0') {
    ElMessage({ type: 'success', message: '删除成功' })
    await pageFn(shopList.value.length > 1 ? pn.value : pn.value - 1);
  }
}

//禁用权限
const disableShop = async (id) => {
  const result = await APIShop.reqDisableOrEnableStore(id,1)
  if (result.code === '0') {
    ElMessage({type: 'success', message: '禁用成功'})
    await pageFn()
  }
}

//启用
const enableShop = async (id) => {
  const result = await APIShop.reqDisableOrEnableStore(id,0)
  if (result.code === '0') {
    ElMessage({type: 'success', message: '启用成功'})
    await pageFn()
  }
}

//搜索按钮的回调
// const search = () => {
//   pageFn()
// }
</script>

<script>
export default {
  name: "Shop"
}
</script>

<template>
  <!--  展示数据-->
  <el-card>
    <el-button type="primary" size="default" @click="addShop">添加分店</el-button>
    <!--    展示客户信息-->
    <el-table  style="margin: 10px 0;" border :data="shopList">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="分店名" align="center" prop="name" show-overflow-tooltip></el-table-column>
      <el-table-column label="地址" align="center" prop="address" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="状态" align="center" prop="banFlag" show-overflow-tooltip>
        <template #="{ row }">
<!--          <p v-if="row.banFlag === 0"></p>-->
<!--          <el-tag v-else type="danger">禁用</el-tag>-->
          <el-tag v-if="row.banFlag === 0" type="success">运营中</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{ row, $index }">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" icon="Edit" @click="updateShop(row)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-popconfirm :title="`确定删除?`" width="260px" @confirm="deleteShop(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-button type="warning" size="small" icon="Edit" @click="disableShop(row.id)">禁用</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="success" size="small" icon="Edit" @click="enableShop(row.id)">启用</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <RouterLink :to="`/log/deal/product-number/?storeId=${row.id}`">
                <el-button :style="{ backgroundColor: '#7e57c2', color: '#fff', borderColor: '#7e57c2' }" size="small">货品订单数量管理</el-button>
              </RouterLink>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <RouterLink :to="`/log/deal/product-payment/?storeId=${row.id}`">
                <el-button  :style="{ backgroundColor: '#ff7043', color: '#fff', borderColor: '#ff7043' }" size="small">货品订单金额管理</el-button>
              </RouterLink>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        @size-change="pageFn()"
        @current-change="pageFn"
        v-model:current-page="pn"
        v-model:page-size="ps"
        :page-sizes="[3, 5, 7, 10]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
    />
  </el-card>

  <el-dialog
      v-model="dialogFormVisible"
      :title="shopParams.id ? '修改分店' : '添加分店'"
  >
    <el-form style="width: 80%" :model="shopParams">
      <el-form-item label="分店名" label-width="100px" prop="realName">
        <el-input v-model="shopParams.name"></el-input>
      </el-form-item>
      <el-form-item label="地址" label-width="100px" prop="realName">
        <el-input v-model="shopParams.address"></el-input>
      </el-form-item>
    </el-form>
    <!-- 具名插槽:footer -->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">
        取消
      </el-button>
      <el-button type="primary" size="default" @click="save">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="css">
.search-card {
  display: flex;
  align-items: center;
  flex-direction: row;
}
.search-input {
  display: flex;
  align-items: center;
  flex: 1 0 auto;
}
.search-input > * {
  flex: 0 1 auto;
  margin-right: 2rem;
}
.search-card .el-form-item {
  margin-bottom: 0;
}
.el-card {
  margin-bottom: 2rem;
}
</style>